package com.whh.business.controller;


import com.whh.business.entry.aaaXml.Root;
import com.whh.business.entry.bbb.BookRoot;
import com.whh.parseData.parseXml.ParseXml;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
public class FileUploadController {
    @PostMapping("/upload/parseXml")
    @ResponseBody
    public Result ParseXml(HttpServletRequest request, HttpServletResponse response) throws Exception {
        File localFile = null;
        try {
            MultipartHttpServletRequest mreq;
            if (request instanceof MultipartHttpServletRequest) {
                mreq = (MultipartHttpServletRequest)request;
            } else {
                return new Result(500,null);
            }
            MultipartFile multipartFile = mreq.getFile("file");
            File file = new File(multipartFile.getOriginalFilename());
            multipartFile.transferTo(file);

            Object obj = null;
            // 类型处理
            localFile = new File("D:\\tmp\\fileUpload\\" + file.getPath());
            String xmlFileType = ParseXml.xmlFile.getXmlFileType(localFile);
            if ("aaa".equals(xmlFileType)) {
                obj = ParseXml.parse(localFile, Root.class);
            } else if ("bbb".equals(xmlFileType)) {
                obj = ParseXml.parse(localFile, BookRoot.class);
            }
            System.out.println(obj);
            //todo 实现业务逻辑
            return new Result(200,obj);
        } finally {
            localFile.delete();
        }
    }

    @GetMapping("/")
    public String uploadPage(){
        return "upload";
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    class Result{
        int code;
        Object object;
    }
}
